package com.george.auth.component.application;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @title: ApplicationContextHandle.java
 * @description:
 * @author: George.Dong
 * @date: 2024/3/5 15:08
 */
@Component
public class ApplicationContextHandle implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public ApplicationContextHandle() {
    }

    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (ApplicationContextHandle.applicationContext == null) {
            ApplicationContextHandle.applicationContext = applicationContext;
        }

        System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext=" + ApplicationContextHandle.applicationContext + "========");
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
